<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\BaseController;
use app\middleware\api\CheckLogin;
use app\model\ProductSku;
use app\model\Specs;
use app\validate\api\CheckId;
use think\Request;

class Product extends BaseController
{

    protected $middleware=[CheckLogin::class];

    /**
     * 全部商品
     * @param int $limit
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index($limit=10)
    {
        $name=\request()->param('name','');
        return $this->success( \app\model\Product::with(['collect'=>function($query){
            $query->where('users_id',request()->userid);
        }])->when($name,function ($query) use ($name){
            $query->where('name','like',"%{$name}%");
        })->where('statusdata',1)->paginate($limit));
    }

    /**
     * 热门产品
     * @return \think\response\Json
     */
    public function hotProducts($limit=10)
    {
        return $this->success(\app\model\Product::getHotProducts($limit,request()->userid));
    }

    /**
     * 产品详情
     * @return \think\response\Json
     * @throws \app\lib\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail()
    {
        (new CheckId())->goCheck();
        $id=request()->param('id');

        \app\model\Product::where('id',$id)->inc('browse',1)->update();

        $status=\app\model\Product::where('id',$id)->value('is_spec');
        if($status){
         $products= ProductSku::where('products_id',$id)->select()->toArray();

            $spec=array_unique(explode('_',implode('_',array_column($products,'specs_value_id'))));
             $res= Specs::with(['spec'=>function($query) use($spec){
               $query->where('id','in',$spec);
           }
            ])->where('products_id',$id)->select()->toArray();
           $data= \app\model\Product::where('id', $id)
                ->with(['collect'=>function($query){
                    $query->where('users_id',request()->userid);
                }])->field('id,name,category_id,cover_pic,banners,content,integral,units,type,is_spec,browse')->find();
        $data['sku']=$products;
        $data['spec']=$res;
         return $this->success($data);
        }
        return $this->success(\app\model\Product::where('id', $id)
            ->with(['collect'=>function($query){
                $query->where('users_id',request()->userid);
            }])->find());

    }

}

